package pl.sar.auth.gui;

import java.beans.ExceptionListener;

import org.apache.log4j.Logger;

/**
 * TimeoutChecker - checks how long we connect to the server. If we reach the <i>timeoutLength</i> value than
 * thread is finished and throws {@link TimeoutException}.
 * 
 * @see add further links
 * @author created: mkozaczyk on 12-04-2012 14:15:41
 * @author last change: $Author: $ on $Date: $
 * @version $Revision: $
 */
public class TimeoutChecker extends Thread
{
    private static Logger logger = Logger.getLogger( TimeoutChecker.class );

    private int timeoutLength;
    private int timeoutCheckout = 100;
    private int timeElapsed;

    /**
     * Constructor.
     * 
     * @param timeoutLength
     *            Timeout length after we thread will be finished
     * @param handler
     *            Handles the occured Exception
     */
    public TimeoutChecker( int timeoutLength, UncaughtExceptionHandler handler )
    {
        this.timeoutLength = timeoutLength;

        timeElapsed = 0;

        this.setUncaughtExceptionHandler( handler );
    }

    public synchronized void reset()
    {
        timeElapsed = 0;
    }

    @Override
    public void run()
    {
        logger.info( "Server timeout checking..." );
        while( true )
        {
            try
            {
                Thread.sleep( timeoutCheckout );
            }
            catch( InterruptedException ioe )
            {
                logger.info( "Server timeout checking stopped. Connection established." );
                return;
            }

            synchronized( this )
            {
                timeElapsed += timeoutCheckout;

                if( timeElapsed > timeoutLength )
                {
                    getUncaughtExceptionHandler().uncaughtException( this,
                        new TimeoutException( timeoutLength ) );
                    return;
                }
            }
        }
    }
}
